
import re

from urllib import urlencode

from urlparse import urlparse

param = {}

re_fullurl = r'(["\'])(http://.+?)([\s,"\'])'

re_parturl = r'(["\'])((/|//)[^>].+?)(["\'])'


re_parturlcss = r'(url[(])(/.+?)([)])'

domain = ""

proxyAddr = ""



#
# -------------------------
# add proxy url
# -------------------------

def addProxyGo(m):
  param["urlAddr"] = m.group(2)
  return m.group(1)+proxyAddr+urlencode(param)+m.group(3)



#
# -------------------------
# format url full address
# -------------------------
def formatUrlFull(m):
  if m.group(3) == "//":
     return m.group(1)+"http:"+m.group(2)+m.group(4)
  else:
     return m.group(1)+domain+m.group(2)+m.group(4)

#
# -------------------------------
# format url full address in CSS
# -------------------------------
def formatUrlFullCss(m):
  url = domain+m.group(2)
  param["urlAddr"] = url
  return m.group(1)+urlparse(proxyAddr).path+"?"+urlencode(param)+m.group(3)




#
# -------------------------
# convert url to proxy url
# -------------------------
def convertUrlHtml(s):
  s = re.sub(re_parturl,formatUrlFull,s)
  s = re.sub(re_fullurl,addProxyGo,s)
  return s


#
# ----------------------------------
# convert url to proxy url in CSS
# ----------------------------------
def convertUrlCss(s):
  s = re.sub(re_parturlcss,formatUrlFullCss,s)
  return s



#
# --------------------------------------------------
# convert url to proxy url in all files, html/css/js
# --------------------------------------------------
def convertUrl(s):
  s = convertUrlHtml(s)
  s = convertUrlCss(s)
  return s







# list all url with format "http://..."

def listFullUrl(s):
  index = 1
  for m in re.finditer(re_fullurl,s):
     print index,":", m.group(0)
     index = index +1
  return s


# list part url with format /... or //...

def listPartUrl(s):
  index = 1
  for m in re.finditer(re_parturl,s):
     print index,":", m.group(0)
     index = index +1
  return s


def listPartUrlCss(s):
  index = 1
  for m in re.finditer(re_parturlcss,s):
     print index,":", m.group(1)
     index = index +1
  return s

